package xyz.scootaloo.kami.server.controller.handler

import io.vertx.core.http.HttpMethod
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.CorsHandler

/**
 * @author flutterdash@qq.com
 * @since 2022/2/6 18:06
 */

fun attachCorsHandler(mountPoint: String, router: Router) {
    router.route("${mountPoint}*").handler(corsHandler())
}

private fun corsHandler() = CorsHandler.create("*")
    .maxAgeSeconds(600)
    .allowedHeaders(corsAllowedHeaders())
    .allowedMethods(corsAllowedMethods())

private fun corsAllowedMethods() = setOf(
    HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS,
    HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.PUT,
    HttpMethod.PATCH
)

private fun corsAllowedHeaders() = setOf(
    "Content-Type", "Accept", "Access-Control-Allow-Origin",
    "origin", "x-requested-with", "Authorization"
)